<template>
  <div class="simple-monaco-editor" ref="editorContainer"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as monaco from 'monaco-editor'
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'

// 配置 Monaco Editor 的 Web Worker
if (typeof self !== 'undefined') {
  self.MonacoEnvironment = {
    getWorker(_, label) {
      try {
        // 根据不同的文件类型返回对应的 Worker
        if (label === 'json') return new jsonWorker()
        if (label === 'css' || label === 'scss' || label === 'less') return new cssWorker()
        if (label === 'html' || label === 'handlebars' || label === 'razor') return new htmlWorker()
        if (label === 'typescript' || label === 'javascript') return new tsWorker()
        return new editorWorker()
      } catch (error) {
        console.warn('Worker 创建失败:', error)
        return new editorWorker()
      }
    }
  }
}

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'html'
  },
  theme: {
    type: String,
    default: 'dark'
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  showLineNumbers: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// Refs
const editorContainer = ref(null)
let editor = null
let completionProviders = [] // 存储补全提供器以便清理

// 编辑器配置
const getEditorOptions = () => {
  // 根据语言选择合适的主题
  let theme = props.theme === 'dark' ? 'monokai' : 'vs'
  if (props.language === 'vue' && props.theme === 'dark') {
    theme = 'vue-monokai'
  }

  return {
    value: props.modelValue || '',
    language: props.language,
    theme: theme,
    readOnly: props.readOnly,
    automaticLayout: true,
    fontSize: 16,
    lineNumbers: props.showLineNumbers ? 'on' : 'off',
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    wordWrap: 'on',
    tabSize: 2,

    insertSpaces: true,
    folding: true,
    bracketPairColorization: { enabled: true },
    guides: {
      bracketPairs: true,
      indentation: true
    },
    suggest: {
      showKeywords: true,
      showSnippets: true,
      showFunctions: true,
      showVariables: true,
      showMethods: true,
      showConstructors: true,
      showModules: true,
      showProperties: true,
      showEvents: true,
      showOperators: true,
      showClasses: true,
      showInterfaces: true,
      showStructs: true,
      showTypeParameters: true,
      showConstants: true,
      showEnums: true,
      showEnumMembers: true,
      showReferences: true,
      showFolders: true,
      showFiles: true,
      showColors: true
    },
    quickSuggestions: {
      other: true,
      comments: false,
      strings: true
    },
    quickSuggestionsDelay: 100,
    acceptSuggestionOnEnter: 'on',
    acceptSuggestionOnCommitCharacter: true,
    suggestOnTriggerCharacters: true,
    wordBasedSuggestions: true,
    tabCompletion: 'on',
    accessibilitySupport: 'off',
    contextmenu: true,
    mouseWheelZoom: true,
    smoothScrolling: true,
    cursorBlinking: 'blink',
    renderLineHighlight: 'line',
    selectOnLineNumbers: true,
    scrollbar: {
      vertical: 'visible',
      horizontal: 'visible',
      verticalScrollbarSize: 10,
      horizontalScrollbarSize: 10
    },
    // 添加上下内边距
    padding: {
      top: 20,
      bottom: 20
    },
    // 禁用可能导致问题的功能
    lightbulb: { enabled: false },
    codeActionsOnSave: { enabled: false },
    codeActionsOnSaveTimeout: 0
  }
}

// 初始化编辑器
const initEditor = () => {
  if (!editorContainer.value) return

  try {
    // 清理之前的补全提供器（如果有的话）- 使用安全的清理函数
    completionProviders.forEach((provider) => {
      safeDispose(provider)
    })
    completionProviders = []

    // 首先设置Vue语言支持
    setupVueLanguageSupport()

    // 创建编辑器
    try {
      editor = monaco.editor.create(editorContainer.value, getEditorOptions())
    } catch (createError) {
      console.error('创建编辑器失败:', createError)
      // 尝试使用更简单的配置重新创建
      const simpleOptions = {
        value: props.modelValue || '',
        language: props.language,
        theme: props.theme === 'dark' ? 'vs-dark' : 'vs',
        readOnly: props.readOnly,
        automaticLayout: true,
        fontSize: 15,
        lineNumbers: props.showLineNumbers ? 'on' : 'off',
        minimap: { enabled: false },
        wordWrap: 'on',
        tabSize: 2,
        insertSpaces: true,
        padding: {
          top: 16,
          bottom: 16
        }
      }
      editor = monaco.editor.create(editorContainer.value, simpleOptions)
    }

    // 监听内容变化
    editor.onDidChangeModelContent(() => {
      const value = editor.getValue()
      emit('update:modelValue', value)
      emit('change', value)
    })

    // 添加Tab键触发补全的智能绑定
    editor.addCommand(monaco.KeyCode.Tab, () => {
      const position = editor.getPosition()
      const model = editor.getModel()
      const lineContent = model.getLineContent(position.lineNumber)
      const word = model.getWordAtPosition(position)

      // 检查是否有活跃的补全建议
      const suggestController = editor.getContribution('editor.contrib.suggestController')

      if (suggestController && suggestController.model && suggestController.model.state !== 0) {
        // 有活跃的建议，接受选中的建议
        editor.trigger('keyboard', 'acceptSelectedSuggestion', {})
      } else if (word || lineContent.trim()) {
        // 有单词或内容，触发补全
        editor.trigger('keyboard', 'editor.action.triggerSuggest', {})
      } else {
        // 没有内容，插入普通的Tab缩进
        editor.trigger('keyboard', 'tab', {})
      }
    })

    // 确保补全功能正常工作
    setTimeout(() => {
      if (editor && !props.modelValue) {
        // 只有在没有初始内容时才设置光标位置
        editor.setPosition({ lineNumber: 1, column: 1 })
      }
    }, 100)
  } catch (error) {
    console.error('❌ Monaco Editor 初始化失败:', error)
  }
}

// 设置Vue语言支持
const setupVueLanguageSupport = () => {
  try {
    // 注册Vue语言
    monaco.languages.register({ id: 'vue' })

    // Vue 3 Composition API 建议
    const vueCompositionAPI = [
      // 响应式API
      { label: 'ref', insertText: 'ref(${1:0})', doc: 'Creates a reactive reference' },
      { label: 'reactive', insertText: 'reactive(${1:{}})', doc: 'Creates a reactive object' },
      { label: 'readonly', insertText: 'readonly(${1:object})', doc: 'Creates a readonly proxy' },
      { label: 'computed', insertText: 'computed(() => ${1:value})', doc: 'Creates a computed property' },
      { label: 'watch', insertText: 'watch(${1:source}, (newVal, oldVal) => {\n  ${2:// handle change}\n})', doc: 'Watches reactive data changes' },
      { label: 'watchEffect', insertText: 'watchEffect(() => {\n  ${1:// effect logic}\n})', doc: 'Runs a function immediately and re-runs when dependencies change' },

      // 生命周期钩子
      { label: 'onMounted', insertText: 'onMounted(() => {\n  ${1:// lifecycle logic}\n})', doc: 'Component mounted lifecycle hook' },
      { label: 'onUpdated', insertText: 'onUpdated(() => {\n  ${1:// lifecycle logic}\n})', doc: 'Component updated lifecycle hook' },
      { label: 'onUnmounted', insertText: 'onUnmounted(() => {\n  ${1:// cleanup logic}\n})', doc: 'Component unmounted lifecycle hook' },
      { label: 'onBeforeMount', insertText: 'onBeforeMount(() => {\n  ${1:// lifecycle logic}\n})', doc: 'Component before mount lifecycle hook' },
      { label: 'onBeforeUpdate', insertText: 'onBeforeUpdate(() => {\n  ${1:// lifecycle logic}\n})', doc: 'Component before update lifecycle hook' },
      { label: 'onBeforeUnmount', insertText: 'onBeforeUnmount(() => {\n  ${1:// cleanup logic}\n})', doc: 'Component before unmount lifecycle hook' },

      // 其他Composition API
      { label: 'toRef', insertText: 'toRef(${1:object}, ${2:key})', doc: 'Creates a ref for a property on a reactive object' },
      { label: 'toRefs', insertText: 'toRefs(${1:object})', doc: 'Converts a reactive object to plain object with refs' },
      { label: 'unref', insertText: 'unref(${1:val})', doc: 'Returns the inner value if the argument is a ref' },
      { label: 'isRef', insertText: 'isRef(${1:val})', doc: 'Checks if a value is a ref object' },
      { label: 'isProxy', insertText: 'isProxy(${1:val})', doc: 'Checks if an object is a proxy created by reactive or readonly' },
      { label: 'isReactive', insertText: 'isReactive(${1:val})', doc: 'Checks if an object is a reactive proxy' },
      { label: 'isReadonly', insertText: 'isReadonly(${1:val})', doc: 'Checks if an object is a readonly proxy' },

      // 工具函数
      { label: 'nextTick', insertText: 'nextTick(() => {\n  ${1:// DOM updated}\n})', doc: 'Defer the callback to be executed after the next DOM update cycle' },
      { label: 'defineProps', insertText: 'defineProps<{\n  ${1:prop}: ${2:string}\n}>()', doc: 'Define component props with TypeScript' },
      { label: 'defineEmits', insertText: 'defineEmits<{\n  ${1:event}: [${2:payload}]\n}>()', doc: 'Define component emits with TypeScript' },
      { label: 'defineExpose', insertText: 'defineExpose({\n  ${1:method}\n})', doc: 'Expose properties to parent component' },
      { label: 'withDefaults', insertText: 'withDefaults(defineProps<${1:Props}>(), {\n  ${2:defaultProp}: ${3:defaultValue}\n})', doc: 'Provide default values for props' }
    ]

    // Vue指令建议
    const vueDirectives = [
      { label: 'v-if', insertText: 'v-if="${1:condition}"', doc: 'Conditionally render element' },
      { label: 'v-else-if', insertText: 'v-else-if="${1:condition}"', doc: 'Else if condition for v-if' },
      { label: 'v-else', insertText: 'v-else', doc: 'Else condition for v-if' },
      { label: 'v-show', insertText: 'v-show="${1:condition}"', doc: 'Toggle element visibility' },
      { label: 'v-for', insertText: 'v-for="${1:item} in ${2:items}" :key="${3:item.id}"', doc: 'Render list of elements' },
      { label: 'v-model', insertText: 'v-model="${1:value}"', doc: 'Two-way data binding' },
      { label: 'v-bind', insertText: 'v-bind:${1:attr}="${2:value}"', doc: 'Bind attribute to expression' },
      { label: 'v-on', insertText: 'v-on:${1:event}="${2:handler}"', doc: 'Listen to DOM events' },
      { label: 'v-text', insertText: 'v-text="${1:text}"', doc: 'Set element textContent' },
      { label: 'v-html', insertText: 'v-html="${1:html}"', doc: 'Set element innerHTML' },
      { label: 'v-pre', insertText: 'v-pre', doc: 'Skip compilation for this element' },
      { label: 'v-cloak', insertText: 'v-cloak', doc: 'Hide element until Vue compilation is done' },
      { label: 'v-once', insertText: 'v-once', doc: 'Render element only once' },
      { label: 'v-memo', insertText: 'v-memo="[${1:dependency}]"', doc: 'Memoize template sub-tree' }
    ]

    // Vue导入建议
    const vueImportSuggestions = [
      // 基础导入
      {
        label: "import { ref } from 'vue'",
        insertText: "import { ref } from 'vue'",
        doc: 'Import ref from Vue'
      },
      {
        label: "import { reactive } from 'vue'",
        insertText: "import { reactive } from 'vue'",
        doc: 'Import reactive from Vue'
      },
      {
        label: "import { computed } from 'vue'",
        insertText: "import { computed } from 'vue'",
        doc: 'Import computed from Vue'
      },
      {
        label: "import { watch } from 'vue'",
        insertText: "import { watch } from 'vue'",
        doc: 'Import watch from Vue'
      },
      {
        label: "import { watchEffect } from 'vue'",
        insertText: "import { watchEffect } from 'vue'",
        doc: 'Import watchEffect from Vue'
      },

      // 生命周期导入
      {
        label: "import { onMounted } from 'vue'",
        insertText: "import { onMounted } from 'vue'",
        doc: 'Import onMounted lifecycle hook'
      },
      {
        label: "import { onUnmounted } from 'vue'",
        insertText: "import { onUnmounted } from 'vue'",
        doc: 'Import onUnmounted lifecycle hook'
      },
      {
        label: "import { onUpdated } from 'vue'",
        insertText: "import { onUpdated } from 'vue'",
        doc: 'Import onUpdated lifecycle hook'
      },

      // 多个API导入
      {
        label: "import { ref, reactive, computed } from 'vue'",
        insertText: "import { ${1:ref, reactive, computed} } from 'vue'",
        doc: 'Import multiple reactive APIs from Vue'
      },
      {
        label: "import { onMounted, onUnmounted } from 'vue'",
        insertText: "import { ${1:onMounted, onUnmounted} } from 'vue'",
        doc: 'Import multiple lifecycle hooks from Vue'
      },

      // 完整导入
      {
        label: "import { ref, reactive, computed, watch, onMounted } from 'vue'",
        insertText: "import { ${1:ref, reactive, computed, watch, onMounted} } from 'vue'",
        doc: 'Import common Vue APIs'
      },

      // 工具函数导入
      {
        label: "import { nextTick } from 'vue'",
        insertText: "import { nextTick } from 'vue'",
        doc: 'Import nextTick from Vue'
      },
      {
        label: "import { toRef, toRefs } from 'vue'",
        insertText: "import { ${1:toRef, toRefs} } from 'vue'",
        doc: 'Import ref utilities from Vue'
      },

      // 路由导入
      {
        label: "import { useRouter } from 'vue-router'",
        insertText: "import { useRouter } from 'vue-router'",
        doc: 'Import useRouter from Vue Router'
      },
      {
        label: "import { useRoute } from 'vue-router'",
        insertText: "import { useRoute } from 'vue-router'",
        doc: 'Import useRoute from Vue Router'
      },

      // Pinia导入
      {
        label: "import { useStore } from 'pinia'",
        insertText: "import { useStore } from 'pinia'",
        doc: 'Import useStore from Pinia'
      },
      {
        label: "import { defineStore } from 'pinia'",
        insertText: "import { defineStore } from 'pinia'",
        doc: 'Import defineStore from Pinia'
      },

      // VueUse导入
      {
        label: "import { useMouse } from '@vueuse/core'",
        insertText: "import { ${1:useMouse} } from '@vueuse/core'",
        doc: 'Import VueUse composables'
      },
      {
        label: "import { useLocalStorage } from '@vueuse/core'",
        insertText: "import { useLocalStorage } from '@vueuse/core'",
        doc: 'Import useLocalStorage from VueUse'
      },

      // Ant Design Vue导入
      {
        label: "import { message } from 'ant-design-vue'",
        insertText: "import { message } from 'ant-design-vue'",
        doc: 'Import message from Ant Design Vue'
      }
    ]

    // Vue API使用情况检测和自动导入建议
    const detectMissingImports = (model, position) => {
      const content = model.getValue()
      const suggestions = []

      // 检测是否使用了Vue API但没有导入
      const vueAPIUsage = [
        { api: 'ref', importStatement: "import { ref } from 'vue'" },
        { api: 'reactive', importStatement: "import { reactive } from 'vue'" },
        { api: 'computed', importStatement: "import { computed } from 'vue'" },
        { api: 'watch', importStatement: "import { watch } from 'vue'" },
        { api: 'watchEffect', importStatement: "import { watchEffect } from 'vue'" },
        { api: 'onMounted', importStatement: "import { onMounted } from 'vue'" },
        { api: 'onUnmounted', importStatement: "import { onUnmounted } from 'vue'" },
        { api: 'nextTick', importStatement: "import { nextTick } from 'vue'" },
        { api: 'toRef', importStatement: "import { toRef } from 'vue'" },
        { api: 'toRefs', importStatement: "import { toRefs } from 'vue'" }
      ]

      vueAPIUsage.forEach(({ api, importStatement }) => {
        // 检查是否使用了API
        const apiUsageRegex = new RegExp(`\\b${api}\\s*\\(`, 'g')
        const isAPIUsed = apiUsageRegex.test(content)

        // 检查是否已经导入了
        const importRegex = new RegExp(`import\\s*{[^}]*\\b${api}\\b[^}]*}\\s*from\\s*['"]vue['"]`, 'g')
        const isAPIImported = importRegex.test(content)

        if (isAPIUsed && !isAPIImported) {
          suggestions.push({
            label: `🔧 Auto-import: ${importStatement}`,
            kind: monaco.languages.CompletionItemKind.Text,
            insertText: importStatement,
            documentation: `Automatically import ${api} because it's used in the code`,
            range: {
              startLineNumber: 1,
              endLineNumber: 1,
              startColumn: 1,
              endColumn: 1
            },
            sortText: '000' + api // 最高优先级
          })
        }
      })

      return suggestions
    }

    // Vue模板语法建议
    const vueTemplateSnippets = [
      {
        label: 'vue-sfc',
        insertText:
          '<template>\\n  <div class="${1:container}">\\n    ${2:<!-- template content -->}\\n  </div>\\n</template>\\n\\n<' +
          "script setup>\\nimport { ${3:ref} } from 'vue'\\n\\n${4:// component logic}\\n</" +
          'script>\\n\\n<style scoped>\\n.${1:container} {\\n  ${5:/* styles */}\\n}\\n</style>',
        doc: 'Vue 3 Single File Component template'
      },
      {
        label: 'vue-component',
        insertText: '<template>\\n  <div>\\n    ${1:content}\\n  </div>\\n</template>\\n\\n<' + 'script setup>\\n${2:// component logic}\\n</' + 'script>',
        doc: 'Vue 3 component with script setup'
      },
      {
        label: 'vue-props',
        insertText: 'const props = defineProps<{\\n  ${1:propName}: ${2:string}\\n}>()',
        doc: 'Define component props'
      },
      {
        label: 'vue-emits',
        insertText: 'const emit = defineEmits<{\\n  ${1:eventName}: [${2:payload}]\\n}>()',
        doc: 'Define component emits'
      }
    ]

    // 统一的Vue API补全提供器 - 支持所有语言
    const vueAPIProvider = monaco.languages.registerCompletionItemProvider(['javascript', 'typescript', 'vue', 'html'], {
      triggerCharacters: ['.', ' ', '(', 'r', 'c', 'w', 'o', 'n', 'd', 't', 'i'],
      provideCompletionItems: (model, position) => {
        try {
          const lineContent = model.getLineContent(position.lineNumber)
          const word = model.getWordUntilPosition(position)
          const range = {
            startLineNumber: position.lineNumber,
            endLineNumber: position.lineNumber,
            startColumn: word.startColumn,
            endColumn: word.endColumn
          }

          const suggestions = []

          // 检测缺失的导入并提供自动导入建议
          try {
            const missingImports = detectMissingImports(model, position)
            if (missingImports.length > 0) {
              suggestions.push(...missingImports)
            }
          } catch (error) {
            console.warn('检测缺失导入时出错:', error)
          }

          // 检查是否在导入语句上下文中
          const isImportContext = lineContent.trim().startsWith('import') || lineContent.includes("from '") || lineContent.includes('from "') || position.lineNumber <= 10

          if (isImportContext || word.word === 'import') {
            // 提供导入建议
            const importSuggestions = vueImportSuggestions.map((importItem) => ({
              label: importItem.label,
              kind: monaco.languages.CompletionItemKind.Module,
              insertText: importItem.insertText,
              insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
              documentation: importItem.doc,
              range: range,
              sortText: '0' + importItem.label
            }))
            suggestions.push(...importSuggestions)
          }

          // 总是提供Vue API建议
          const apiSuggestions = vueCompositionAPI.map((api) => ({
            label: api.label,
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: api.insertText,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: api.doc,
            range: range,
            sortText: '1' + api.label,
            detail: 'Vue 3 Composition API'
          }))
          suggestions.push(...apiSuggestions)

          // 如果是HTML语言，添加Vue模板语法补全
          const currentLanguage = model.getLanguageId()
          if (currentLanguage === 'html') {
            // 添加Vue模板语法
            const templateSuggestions = [
              { label: '{{ }}', insertText: '{{ ${1:expression} }}', doc: 'Vue interpolation' },
              { label: 'v-if', insertText: 'v-if="${1:condition}"', doc: 'Conditional rendering' },
              { label: 'v-for', insertText: 'v-for="${1:item} in ${2:items}" :key="${3:item.id}"', doc: 'List rendering' },
              { label: 'v-model', insertText: 'v-model="${1:value}"', doc: 'Two-way binding' },
              { label: '@click', insertText: '@click="${1:handler}"', doc: 'Click event' },
              { label: ':class', insertText: ':class="${1:classes}"', doc: 'Dynamic class binding' },
              { label: ':style', insertText: ':style="${1:styles}"', doc: 'Dynamic style binding' },
              { label: 'ref', insertText: 'ref="${1:refName}"', doc: 'Template ref' }
            ]

            const htmlSuggestions = templateSuggestions.map((tmpl) => ({
              label: tmpl.label,
              kind: monaco.languages.CompletionItemKind.Snippet,
              insertText: tmpl.insertText,
              insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
              documentation: tmpl.doc,
              range: range,
              sortText: '0' + tmpl.label,
              detail: 'Vue Template'
            }))
            suggestions.push(...htmlSuggestions)
          }

          return { suggestions }
        } catch (error) {
          console.error('❌ Vue API补全提供器错误:', error)
          return { suggestions: [] }
        }
      }
    })

    // 只存储有dispose方法的提供器
    if (vueAPIProvider && typeof vueAPIProvider.dispose === 'function') {
      completionProviders.push(vueAPIProvider)
    }

    // 为HTML提供Vue指令补全
    const vueDirectiveProvider = monaco.languages.registerCompletionItemProvider(['html', 'vue'], {
      provideCompletionItems: (model, position) => {
        const word = model.getWordUntilPosition(position)
        const range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn
        }

        const suggestions = [
          ...vueDirectives.map((directive) => ({
            label: directive.label,
            kind: monaco.languages.CompletionItemKind.Property,
            insertText: directive.insertText,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: directive.doc,
            range: range
          })),
          ...vueTemplateSnippets.map((snippet) => ({
            label: snippet.label,
            kind: monaco.languages.CompletionItemKind.Snippet,
            insertText: snippet.insertText,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: snippet.doc,
            range: range
          }))
        ]

        return { suggestions }
      }
    })

    // 只存储有dispose方法的提供器
    if (vueDirectiveProvider && typeof vueDirectiveProvider.dispose === 'function') {
      completionProviders.push(vueDirectiveProvider)
    }

    // 设置Vue语言的配置
    monaco.languages.setMonarchTokensProvider('vue', {
      tokenizer: {
        root: [
          [/<template[^>]*>/, 'tag.template.open', '@template'],
          [/<script[^>]*>/, 'tag.script.open', '@script'],
          [/<style[^>]*>/, 'tag.style.open', '@style'],
          [/<!--/, 'comment', '@comment'],
          [/<\/?[a-zA-Z][\w-]*/, 'tag'],
          [/{{.*?}}/, 'interpolation'],
          [/v-[a-zA-Z-]+/, 'directive'],
          [/:[\w-]+/, 'attribute.bind'],
          [/@[\w-]+/, 'attribute.event']
        ],
        template: [
          [/<\/template>/, 'tag.template.close', '@pop'],
          [/{{.*?}}/, 'interpolation'],
          [/v-[a-zA-Z-]+/, 'directive'],
          [/:[\w-]+/, 'attribute.bind'],
          [/@[\w-]+/, 'attribute.event'],
          [/<[^>]+>/, 'tag'],
          [/[^<]+/, 'text']
        ],
        script: [
          [/<\/script>/, 'tag.script.close', '@pop'],
          [/[^<]+/, 'script.content']
        ],
        style: [
          [/<\/style>/, 'tag.style.close', '@pop'],
          [/[^<]+/, 'style.content']
        ],
        comment: [
          [/-->/, 'comment', '@pop'],
          [/[^-]+/, 'comment.content']
        ]
      }
    })

    // 定义 Monokai 主题
    monaco.editor.defineTheme('monokai', {
      base: 'vs-dark',
      inherit: true,
      rules: [
        { token: '', foreground: 'F8F8F2', background: '272822' },
        { token: 'comment', foreground: '75715E', fontStyle: 'italic' },
        { token: 'keyword', foreground: 'F92672', fontStyle: 'bold' },
        { token: 'keyword.operator', foreground: 'F92672' },
        { token: 'string', foreground: 'E6DB74' },
        { token: 'string.escape', foreground: 'AE81FF' },
        { token: 'number', foreground: 'AE81FF' },
        { token: 'regexp', foreground: 'FD971F' },
        { token: 'type', foreground: '66D9EF', fontStyle: 'italic' },
        { token: 'variable', foreground: 'F8F8F2' },
        { token: 'variable.parameter', foreground: 'FD971F', fontStyle: 'italic' },
        { token: 'entity.name.function', foreground: 'A6E22E' },
        { token: 'entity.name.class', foreground: 'A6E22E', fontStyle: 'underline' },
        { token: 'entity.name.type', foreground: '66D9EF', fontStyle: 'italic' },
        { token: 'entity.other.attribute-name', foreground: 'A6E22E' },
        { token: 'entity.other.attribute-name.class', foreground: 'A6E22E', fontStyle: 'underline' },
        { token: 'entity.other.attribute-name.id', foreground: 'A6E22E', fontStyle: 'underline' },
        { token: 'meta.tag', foreground: 'F8F8F2' },
        { token: 'meta.tag.sgml', foreground: 'F8F8F2' },
        { token: 'meta.selector', foreground: 'F92672' },
        { token: 'entity.name.tag', foreground: 'F92672' },
        { token: 'punctuation.definition.tag.html', foreground: 'F8F8F2' },
        { token: 'punctuation.definition.tag.begin.html', foreground: 'F8F8F2' },
        { token: 'punctuation.definition.tag.end.html', foreground: 'F8F8F2' }
      ],
      colors: {
        'editor.background': '#272822',
        'editor.foreground': '#F8F8F2',
        'editorCursor.foreground': '#F8F8F0',
        'editor.lineHighlightBackground': '#3E3D32',
        'editorLineNumber.foreground': '#90908A',
        'editor.selectionBackground': '#49483E',
        'editor.inactiveSelectionBackground': '#49483E',
        'editorWhitespace.foreground': '#3B3A32',
        'editorIndentGuide.background': '#3B3A32',
        'editorIndentGuide.activeBackground': '#9D550FB0',
        'editor.selectionHighlightBorder': '#222218',
        'editorSuggestWidget.background': '#272822',
        'editorSuggestWidget.border': '#3E3D32',
        'editorSuggestWidget.foreground': '#F8F8F2',
        'editorSuggestWidget.highlightForeground': '#F92672',
        'editorSuggestWidget.selectedBackground': '#414339',
        'editorHoverWidget.background': '#272822',
        'editorHoverWidget.border': '#3E3D32'
      }
    })

    // 定义Vue语法高亮主题（基于Monokai）
    monaco.editor.defineTheme('vue-monokai', {
      base: 'vs-dark',
      inherit: true,
      rules: [
        { token: '', foreground: 'F8F8F2', background: '272822' },
        { token: 'comment', foreground: '75715E', fontStyle: 'italic' },
        { token: 'tag.template.open', foreground: 'F92672' },
        { token: 'tag.template.close', foreground: 'F92672' },
        { token: 'tag.script.open', foreground: 'A6E22E' },
        { token: 'tag.script.close', foreground: 'A6E22E' },
        { token: 'tag.style.open', foreground: '66D9EF' },
        { token: 'tag.style.close', foreground: '66D9EF' },
        { token: 'interpolation', foreground: 'FD971F', fontStyle: 'bold' },
        { token: 'directive', foreground: 'AE81FF', fontStyle: 'bold' },
        { token: 'attribute.bind', foreground: 'A6E22E' },
        { token: 'attribute.event', foreground: 'F92672' },
        { token: 'tag', foreground: 'F92672' },
        { token: 'keyword', foreground: 'F92672', fontStyle: 'bold' },
        { token: 'string', foreground: 'E6DB74' },
        { token: 'number', foreground: 'AE81FF' },
        { token: 'variable', foreground: 'F8F8F2' },
        { token: 'entity.name.function', foreground: 'A6E22E' }
      ],
      colors: {
        'editor.background': '#272822',
        'editor.foreground': '#F8F8F2',
        'editorCursor.foreground': '#F8F8F0',
        'editor.lineHighlightBackground': '#3E3D32',
        'editorLineNumber.foreground': '#90908A',
        'editor.selectionBackground': '#49483E'
      }
    })

    // 设置Vue语言配置
    monaco.languages.setLanguageConfiguration('vue', {
      comments: {
        blockComment: ['<!--', '-->']
      },
      brackets: [
        ['<', '>'],
        ['{', '}'],
        ['(', ')'],
        ['[', ']']
      ],
      autoClosingPairs: [
        { open: '<', close: '>', notIn: ['string'] },
        { open: '{', close: '}' },
        { open: '(', close: ')' },
        { open: '[', close: ']' },
        { open: '"', close: '"', notIn: ['string'] },
        { open: "'", close: "'", notIn: ['string'] }
      ],
      surroundingPairs: [
        { open: '<', close: '>' },
        { open: '{', close: '}' },
        { open: '(', close: ')' },
        { open: '[', close: ']' },
        { open: '"', close: '"' },
        { open: "'", close: "'" }
      ]
    })
  } catch (error) {
    console.warn('❌ Vue语言支持设置失败:', error)
  }
}

// 监听属性变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (editor && editor.getValue() !== newValue) {
      editor.setValue(newValue || '')
    }
  }
)

watch(
  () => props.language,
  (newLanguage) => {
    if (editor && monaco) {
      const model = editor.getModel()
      monaco.editor.setModelLanguage(model, newLanguage)

      // 切换语言时同时切换合适的主题
      let theme = props.theme === 'dark' ? 'monokai' : 'vs'
      if (newLanguage === 'vue' && props.theme === 'dark') {
        theme = 'vue-monokai'
      }
      monaco.editor.setTheme(theme)
    }
  }
)

watch(
  () => props.theme,
  (newTheme) => {
    if (editor && monaco) {
      // 根据语言和主题选择合适的主题
      let theme = newTheme === 'dark' ? 'monokai' : 'vs'
      if (props.language === 'vue' && newTheme === 'dark') {
        theme = 'vue-monokai'
      }
      monaco.editor.setTheme(theme)
    }
  }
)

// 公开方法
const getValue = () => {
  return editor ? editor.getValue() : props.modelValue
}

const setValue = (value) => {
  if (editor) {
    editor.setValue(value || '')
  }
}

const focus = () => {
  if (editor) {
    editor.focus()
  }
}

// 测试补全功能
const testCompletion = () => {
  if (editor) {
    // 获取当前模型和语言
    const model = editor.getModel()

    // 手动触发补全
    editor.trigger('test', 'editor.action.triggerSuggest', {})
  }
}

// 强制显示Vue API补全
const forceVueCompletion = () => {
  if (editor) {
    const model = editor.getModel()
    const position = editor.getPosition() || { lineNumber: 1, column: 1 }

    // 创建一个临时的补全项
    const vueAPIs = ['ref', 'reactive', 'computed', 'watch', 'watchEffect', 'onMounted', 'onUnmounted', 'onUpdated', 'nextTick', 'toRef', 'toRefs', 'defineProps', 'defineEmits']

    // 手动创建建议
    const suggestions = vueAPIs.map((api) => ({
      label: api,
      kind: monaco.languages.CompletionItemKind.Function,
      insertText: api + '(${1})',
      insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
      documentation: `Vue 3 Composition API: ${api}`,
      detail: 'Vue 3 API',
      sortText: '0' + api
    }))

    // 注册临时补全提供器
    const disposable = monaco.languages.registerCompletionItemProvider(model.getLanguageId(), {
      provideCompletionItems: () => {
        return { suggestions }
      }
    })

    // 触发补全
    editor.trigger('force', 'editor.action.triggerSuggest', {})

    // 5秒后清理
    setTimeout(() => {
      if (safeDispose(disposable)) {
      }
    }, 5000)
  }
}

// 暴露方法
defineExpose({
  getValue,
  setValue,
  focus,
  testCompletion,
  forceVueCompletion,
  editor: () => editor
})

// 安全的清理函数
const safeDispose = (disposable) => {
  try {
    if (disposable && typeof disposable.dispose === 'function') {
      disposable.dispose()
      return true
    } else if (disposable && typeof disposable === 'function') {
      // 如果disposable本身就是一个dispose函数
      disposable()
      return true
    }
    return false
  } catch (error) {
    console.warn('清理disposable时出错:', error)
    return false
  }
}

// 生命周期
onMounted(() => {
  // 等待DOM渲染完成后初始化
  nextTick(() => {
    setTimeout(initEditor, 100)
  })
})

onUnmounted(() => {
  try {
    // 清理补全提供器 - 使用安全的清理函数
    completionProviders.forEach((provider) => {
      safeDispose(provider)
    })
    completionProviders = []

    // 清理编辑器 - 更全面的清理
    if (editor) {
      try {
        // 获取编辑器模型
        const model = editor.getModel()

        // 先清理编辑器
        editor.dispose()

        // 然后清理模型（如果存在且不是共享模型）
        if (model && !model.isDisposed()) {
          model.dispose()
        }

        editor = null
      } catch (editorError) {
        console.warn('清理编辑器时出错:', editorError)
      }
    }

    // 清理 Monaco Editor 的全局资源
    try {
      // 清理所有注册的语言
      monaco.languages.clear()

      // 清理所有注册的主题
      monaco.editor.clearAllFontInfos()

      // 清理所有注册的模型
      monaco.editor.getModels().forEach((model) => {
        if (!model.isDisposed()) {
          model.dispose()
        }
      })
    } catch (monacoError) {
      console.warn('清理 Monaco Editor 全局资源时出错:', monacoError)
    }
  } catch (error) {
    console.warn('Monaco Editor 清理时出错:', error)
  }
})
</script>

<style scoped>
.simple-monaco-editor {
  width: 100%;
  height: 100%;
  min-height: 400px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  background: #fff;
  position: relative;
}

/* 确保 Monaco Editor 内容区域有适当的内边距 */
.simple-monaco-editor .monaco-editor {
  padding: 16px 0;
}

/* 深色主题 */
.simple-monaco-editor:has(.monaco-editor[data-theme-name*='dark']) {
  border-color: #3e3e3e;
  background: #1e1e1e;
}

/* 深色主题下的内边距 */
.simple-monaco-editor:has(.monaco-editor[data-theme-name*='dark']) .monaco-editor {
  padding: 16px 0;
}

/* 加载状态 */
.simple-monaco-editor:empty::before {
  content: '正在加载编辑器...';
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
  font-size: 14px;
}
</style>
